package com.lockforzookeeper.controller;

import com.lockforzookeeper.common.ZookeeperLock;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author: 顾志杰
 */
@RestController
@Slf4j
public class ZookeeperController {

    @Autowired
    private CuratorFramework client;

    @RequestMapping("zkLock")
    public String zookeeperLock() {
        log.info("我进入了方法！");
        try (ZookeeperLock zkLock = new ZookeeperLock()) {
            if (zkLock.getLock("order")) {
                log.info("我获得了锁");
                Thread.sleep(10000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("方法执行完成！");
        return "方法执行完成！";
    }

    @RequestMapping("curatorLock")
    public String curatorLock() throws Exception {

        log.info("我进入了方法！");
        InterProcessMutex lock = new InterProcessMutex(client, "/order");
        try {
            /*获取锁 超时时间30秒*/
            if (lock.acquire(30, TimeUnit.SECONDS)) {
                log.info("我获得了锁");
                Thread.sleep(10000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            log.info("释放锁");
            lock.release();
        }
        log.info("方法执行完成！");
        return "方法执行完成！";
    }
}
